/**
 * Cobub Razor
 *
 * An open source analytics android sdk for mobile applications
 *
 * @package		Cobub Razor
 * @author		WBTECH Dev Team
 * @copyright	Copyright (c) 2011 - 2012, NanJing Western Bridge Co.,Ltd.
 * @license		http://www.cobub.com/products/cobub-razor/license
 * @link		http://www.cobub.com/products/cobub-razor/
 * @since		Version 0.1
 * @filesource
 */
package com.citywithincity.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.damai.error.ApiError;

public class MD5Util {

	public static String md5Appkey(String content) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(content.getBytes("UTF-8"));
			return getHashString(digest);
		} catch (NoSuchAlgorithmException e) {
			throw new ApiError("NoSuchAlgorithmException");
		} catch (UnsupportedEncodingException e) {
			throw new ApiError("UnsupportedEncodingException");
		}
	}

	private static String getHashString(MessageDigest digest) {
		StringBuilder builder = new StringBuilder();
		for (byte b : digest.digest()) {
			builder.append(Integer.toHexString((b >> 4) & 0xf));
			builder.append(Integer.toHexString(b & 0xf));
		}
		return builder.toString();
	}

	public static String sha1(String decript) {
		return HexUtil.encodeHexStr(sha(decript.getBytes(),"SHA-1"));
	}
	
	public static byte[] sha256(byte[] bytes) {
		return sha(bytes,"SHA-256");
	}
	/**
	 * 字符串 SHA 加密
	 * 
	 * @param strSourceText
	 * @return
	 */
	private static byte[] sha(byte[] src, String type) {
		try {
			// SHA 加密开始
			// 创建加密对象 并傳入加密類型
			MessageDigest messageDigest = MessageDigest.getInstance(type);
			// 传入要加密的字符串
			messageDigest.update(src);
			// 得到 byte 類型结果
			return messageDigest.digest();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("找不到算法", e);
		}

	}

}
